<!-- 仪表盘 -->
<template>
  <el-card style="max-width: 100%;">
    <template #header>
      <div class="card-header">
        <span>农田数据统计分析</span>
      </div>
    </template>
    <!-- 实现统计图的显示 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <div id="userFarmChart" style="width: 100%; height: 350px"></div>
      </el-col>
      <el-col :span="12">
        <div id="cropDistributionChart" style="width: 100%; height: 350px"></div>
      </el-col>
    </el-row>
    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="12">
        <div id="monthlyAddedChart" style="width: 100%; height: 350px"></div>
      </el-col>
      <el-col :span="12">
        <div id="statusDistributionChart" style="width: 100%; height: 350px"></div>
      </el-col>
    </el-row>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import * as echarts from "echarts";

// 加载数据
const loadData = async () => {
  try {
    // 并行请求用户和农田数据
    const [usersRes, farmsRes] = await Promise.all([
      axios.get("http://localhost:3000/users"),
      axios.get("http://localhost:3000/farms")
    ]);

    if (usersRes.statusText === "OK" && farmsRes.statusText === "OK") {
      // 初始化所有图表
      initUserFarmChart(usersRes.data, farmsRes.data);
      initCropDistributionChart(farmsRes.data);
      initMonthlyAddedChart(usersRes.data);
      initStatusDistributionChart(farmsRes.data);
    } else {
      ElMessage.error("获取数据失败");
    }
  } catch (err) {
    console.error(err);
    ElMessage.error("请求数据出错");
  }
};

// 图表1: 用户与农田数量关系
const initUserFarmChart = (users, farms) => {
  const userNames = [];
  const farmCounts = [];
  const farmDetails = [];
  
  users.forEach(user => {
    userNames.push(user.username);
    const userFarms = farms.filter(farm => farm.userId === user.id);
    farmCounts.push(userFarms.length);
    
    // 收集每个用户的农田详情用于tooltip
    const detail = userFarms.map(farm => 
      `${farm.name} (${farm.crop}, ${farm.status})`
    ).join('<br>');
    farmDetails.push(detail);
  });

  const chart = echarts.init(document.getElementById("userFarmChart"));
  const option = {
    title: { text: "用户农田数量及详情" },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: params => {
        return `${params[0].name}<br/>
                农田数量: ${params[0].value}<br/>
                农田详情:<br/>${farmDetails[params[0].dataIndex]}`;
      }
    },
    xAxis: { 
      type: 'category',
      data: userNames,
      axisLabel: { rotate: 30 }
    },
    yAxis: { type: 'value' },
    series: [{
      name: '农田数量',
      type: 'bar',
      data: farmCounts,
      itemStyle: {
        color: function(params) {
          const colorList = ['#c23531','#2f4554','#61a0a8','#d48265','#91c7ae'];
          return colorList[params.dataIndex % colorList.length];
        }
      }
    }]
  };
  chart.setOption(option);
};

// 图表2: 作物类型分布
const initCropDistributionChart = (farms) => {
  const cropMap = {};
  farms.forEach(farm => {
    cropMap[farm.crop] = (cropMap[farm.crop] || 0) + 1;
  });

  const chart = echarts.init(document.getElementById("cropDistributionChart"));
  const option = {
    title: { text: "作物类型分布" },
    tooltip: { trigger: 'item' },
    series: [{
      name: '作物类型',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: true,
        formatter: '{b}: {c} ({d}%)'
      },
      emphasis: {
        label: { show: true }
      },
      data: Object.entries(cropMap).map(([name, value]) => ({ name, value }))
    }]
  };
  chart.setOption(option);
};

// 图表3: 月度新增统计
const initMonthlyAddedChart = (users) => {
  const months = {};
  users.forEach(user => {
    user.farmStats?.monthlyAdded?.forEach(monthData => {
      months[monthData.month] = (months[monthData.month] || 0) + monthData.count;
    });
  });

  const sortedMonths = Object.keys(months).sort();
  const chart = echarts.init(document.getElementById("monthlyAddedChart"));
  const option = {
    title: { text: "月度新增农田统计" },
    tooltip: { trigger: 'axis' },
    xAxis: {
      type: 'category',
      data: sortedMonths
    },
    yAxis: { type: 'value' },
    series: [{
      name: '新增数量',
      type: 'line',
      data: sortedMonths.map(month => months[month]),
      smooth: true,
      lineStyle: { width: 3 },
      symbolSize: 8
    }]
  };
  chart.setOption(option);
};

// 图表4: 农田状态分布
const initStatusDistributionChart = (farms) => {
  const statusMap = {};
  farms.forEach(farm => {
    statusMap[farm.status] = (statusMap[farm.status] || 0) + 1;
  });

  const chart = echarts.init(document.getElementById("statusDistributionChart"));
  const option = {
    title: { text: "农田状态分布" },
    tooltip: { trigger: 'item' },
    series: [{
      name: '农田状态',
      type: 'pie',
      roseType: 'radius',
      radius: [50, 150],
      center: ['50%', '50%'],
      data: Object.entries(statusMap).map(([name, value]) => ({
        name,
        value,
        itemStyle: {
          color: getStatusColor(name)
        }
      })),
      label: { show: true },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  };
  chart.setOption(option);
};

// 状态颜色映射
const getStatusColor = (status) => {
  const colors = {
    '播种期': '#95d475',
    '生长期': '#4caf50',
    '需灌溉': '#64b5f6',
    '需施肥': '#ffb74d'
  };
  return colors[status] || '#9e9e9e';
};

onMounted(() => {
  loadData();
  
  // 窗口大小变化时重新调整图表大小
  window.addEventListener('resize', function() {
    [
      'userFarmChart',
      'cropDistributionChart',
      'monthlyAddedChart',
      'statusDistributionChart'
    ].forEach(id => {
      const chart = echarts.getInstanceByDom(document.getElementById(id));
      chart && chart.resize();
    });
  });
});
</script>

<style>
.card-header {
  
  font-size: 18px;
  font-weight: bold;
  padding: 10px 0;
}
.el-row {
  margin-bottom: 20px;
}
</style>